﻿// Copyright (c) 2012-2013 fancidev
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.IO;
using System.Drawing.Imaging;

namespace Util.Media
{
    internal static class SvgImageCodec
    {
        public static void WriteHeader(StreamWriter writer)
        {
            writer.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            writer.WriteLine("<svg xmlns=\"http://www.w3.org/2000/svg\"" +
                             " xmlns:xlink=\"http://www.w3.org/1999/xlink\">");
        }

        public static void WriteFooter(StreamWriter writer)
        {
            writer.WriteLine("</svg>");
        }

        /// <summary>
        /// Saves an animated image in SVG file format.
        /// </summary>
        /// <param name="img">The image to save.</param>
        /// <param name="filename">The file to save.</param>
        /// Write each image in PNG format.
        public static void WriteFrame(
            StreamWriter writer, 
            System.Drawing.Image frameImage,
            TimeSpan frameDelay,
            int frameIndex, 
            int frameCount,
            ref int startTime)
        {
            // The first frame is initially set to visible. Other frames are
            // initialized to hidden.
            writer.WriteLine("  <g visibility=\"{0}\">",
                frameIndex == 0 ? "visible" : "hidden");

            // SMIL animation to display the image.
            if (frameIndex > 0)
            {
                writer.WriteLine(
                    "    <animate attributeName=\"visibility\"" +
                    " attributeType=\"XML\" calcMode=\"discrete\"" +
                    " begin=\"" + startTime + "ms\" to=\"visible\"/>");
            }

            // SMIL animation to hide the image.
            startTime += (int)frameDelay.TotalMilliseconds;
            if (frameIndex != frameCount - 1)
            {
                writer.WriteLine(
                    "    <animate attributeName=\"visibility\"" +
                    " attributeType=\"XML\" calcMode=\"discrete\"" +
                    " begin=\"" + startTime + "ms\" to=\"hidden\"/>");
            }

            // Write embedded PNG file.
            writer.Write("    <image width=\"" + frameImage.Width + "\" height=\"" +
                frameImage.Height + "\" xlink:href=\"data:image/png;base64,");

            using (MemoryStream mem = new MemoryStream())
            {
                frameImage.Save(mem, ImageFormat.Png);
                writer.Write(Convert.ToBase64String(mem.GetBuffer(), 0, (int)mem.Length));
            }
            writer.WriteLine("\"/>");
            writer.WriteLine("  </g>");
        }
    }

    public class SvgImageEncoder : IDisposable
    {
        private StreamWriter writer;
        private int frameCount;
        private int frameIndex;
        private int startTime;

        public SvgImageEncoder(Stream stream, int frameCount)
        {
            this.writer = new StreamWriter(stream);
            this.frameCount = frameCount;
            this.frameIndex = -1;
            this.startTime = 0;
            SvgImageCodec.WriteHeader(writer);
        }

        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (writer != null)
            {
                SvgImageCodec.WriteFooter(writer);
                writer.Dispose();
                writer = null;
            }
        }

        /// <summary>
        /// Saves an animated image in SVG file format.
        /// </summary>
        /// <param name="img">The image to save.</param>
        /// <param name="filename">The file to save.</param>
        public void EncodeFrame(System.Drawing.Image frameImage, TimeSpan frameDelay)
        {
            SvgImageCodec.WriteFrame(writer, frameImage, frameDelay, ++frameIndex, frameCount, ref startTime);
        }

        public static void Encode(MultiFrameImage image, string fileName)
        {
            using (Stream output = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                Encode(image, output);
            }
        }

        public static void Encode(MultiFrameImage image, Stream stream)
        {
            using (StreamWriter writer = new StreamWriter(stream))
            {
                SvgImageCodec.WriteHeader(writer);
                int startTime = 0;
                for (int i = 0; i < image.FrameCount; i++)
                {
                    image.FrameIndex = i;
                    SvgImageCodec.WriteFrame(writer, image.Frame, image.FrameDelay,
                        i, image.FrameCount, ref startTime);
                }
                SvgImageCodec.WriteFooter(writer);
            }
        }
    }
}
